package com.eol.admin.modules.business.member;

import com.eol.admin.modules.logging.log.Log;
import com.eol.common.exception.BaseException;
import com.eol.common.utils.StringUtils;
import com.eol.entity.po.merchant.ZMerchant;
import com.eol.service.merchant.ZMerchantService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2020/6/5
 * Time: 8:57 PM
 * Description: Merchant
 */
@RestController
@RequestMapping("api/merchant")
public class MerchantController {

    @Resource
    private ZMerchantService zMerchantService;

    @GetMapping
    public ResponseEntity<Object> list(@RequestParam(value = "name", required = false) String name) {
        return new ResponseEntity<>(zMerchantService.buildTree(
                zMerchantService.selectMerchantList(ZMerchant.builder().name(name).build())),
                HttpStatus.OK);
    }

    @Log("新增商户")
    @PreAuthorize("@el.check('merchant:add')")
    @PostMapping
    public ResponseEntity<Object> add(@Validated @RequestBody ZMerchant zMerchant) {
        ZMerchant old = zMerchantService.selectById(zMerchant.getId());
        if (null != old) throw new BaseException("商户代码已经存在");
        zMerchant.setCreateTime(new Date());
        validateType(zMerchant);
        return new ResponseEntity<>(zMerchantService.insertSelective(zMerchant), HttpStatus.OK);
    }

    @Log("编辑商户")
    @PutMapping
    @PreAuthorize("@el.check('merchant:edit')")
    public ResponseEntity<Object> edit(@Validated @RequestBody ZMerchant zMerchant) {
        validateType(zMerchant);
        return new ResponseEntity<>(zMerchantService.updateSelectiveById(zMerchant), HttpStatus.OK);
    }

    @Log("删除商户")
    @DeleteMapping("/{id}")
    @PreAuthorize("@el.check('merchant:del')")
    public ResponseEntity<Object> del(@PathVariable("id") String id) {
        //判断是否存在下级分类
        long b = zMerchantService.selectCount(ZMerchant.builder()
                .pid(id)
                .build());
        if (b > 0)
            throw new BaseException("该分类下存在子分类，不可以删除");
        return new ResponseEntity<>(zMerchantService.deleteById(id), HttpStatus.OK);
    }


    private void validateType(ZMerchant zProductType) {
        if (zProductType.getId().equalsIgnoreCase(zProductType.getPid())) {
            throw new BaseException("上级分类不能是自己");
        }
        if (StringUtils.isNotBlank(zProductType.getPid())) {
            ZMerchant belongto = zMerchantService.selectById(zProductType.getPid());
            if (null == belongto) throw new BaseException("分类不存在");
            if (StringUtils.isNotBlank(belongto.getPid()))
                throw new BaseException("暂不支持三级分类");
        }
    }


}
